package com.chen.shopping_pay_service.service;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayResponse;
import com.alipay.api.request.AlipayTradePageMergePayRequest;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.response.AlipayTradePageMergePayResponse;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.chen.shopping_common.pojo.Orders;
import com.chen.shopping_common.pojo.Payment;
import com.chen.shopping_common.result.BusException;
import com.chen.shopping_common.result.CodeEnum;
import com.chen.shopping_common.service.PayService;
import com.chen.shopping_pay_service.ZfbPayConfig;

import com.chen.shopping_pay_service.mapper.PaymentMapper;
import com.chen.shopping_pay_service.util.ZfbVerifierUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Map;

@DubboService
public class PayServiceImpl implements PayService {

    @Autowired
    private ZfbPayConfig zfbPayConfig;
    @Autowired
    private AlipayClient alipayClient;
    @Autowired
    private PaymentMapper paymentMapper;


    //生成二维码
    @Override
    public String pcPay(Orders orders) {
        /**
         * 判断订单状态：未支付的订单才会生成二维码
         */
        if (orders.getStatus() != 1){
            throw new BusException(CodeEnum.PAYMENT_QRCODE_EXIST_ERROR);
        }


        //创建请求对象
        AlipayTradePrecreateRequest alipayTradePageMergePayRequest = new AlipayTradePrecreateRequest();

        //设置请求内容
        alipayTradePageMergePayRequest.setNotifyUrl(zfbPayConfig.getNotifyUrl()+zfbPayConfig.getPcNotify());
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("out_trade_no",orders.getId());  //设置订单编号
        jsonObject.put("total_amount",orders.getPayment());  //设置订单金额
        jsonObject.put("subject",orders.getCartGoods().get(0).getGoodsName()); //设置订单标题
        alipayTradePageMergePayRequest.setBizContent(jsonObject.toString());

        try {
            //发送请求
            AlipayTradePrecreateResponse execute = alipayClient.execute(alipayTradePageMergePayRequest);
            return execute.getQrCode();
        }catch (AlipayApiException e){
            throw new BusException(CodeEnum.PAYMENT_QRCODE_ERROR);
        }
    }

    @Override
    public void checkSign(Map<String, Object> paramMap) {
        Map<String,String[]> requestParameterMap = (Map<String,String[]>) paramMap.get("requestParameterMap");
        boolean valid = ZfbVerifierUtils.isValid(requestParameterMap, zfbPayConfig.getPublicKey());
        //验签失败，抛出异常
        if (!valid){
            throw new BusException(CodeEnum.PAYMENT_CHECKSIGN_ERROR);
        }
    }

    //保存支付信息
    @Override
    public void addPayment(Payment payment) {
        paymentMapper.insert(payment);
    }
}
